﻿using NetMQ;
using NetMQ.Sockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NETMQLib
{


    public class InprocServerMQ
    {
        NetMQ.Sockets.PairSocket pairSocket = null;
        string url = "";
        public BaseMQModel BaseMQInfo { get; set; }
        public event Func<string, string> ReceiveFrameStringEvent;

        public InprocServerMQ(string title)
        {
            BaseMQInfo = new BaseMQModel() { Title = title };
            url = $"inproc://{title}";
            pairSocket = new NetMQ.Sockets.PairSocket();
            pairSocket.Bind(url);
            Thread recvThread = new Thread(new ThreadStart(RecvHand));
            recvThread.Start();
        }

        private void RecvHand()
        {
            while (true)
            {
                try
                {
                    string msg = pairSocket.ReceiveFrameString(out bool hasMore);
                    if (msg == "exit")
                    {
                        break;
                    }
                    string backMsg = ReceiveFrameStringEvent?.Invoke(msg);
                    pairSocket.SendFrame(backMsg, hasMore);
                }
                catch
                {
                    if (pairSocket.IsDisposed)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                    continue;
                }
            }
        }
    }
}
